<template>
	<a-form-item-rest>
		<a-select
			v-if="!isEmbed"
			:class="[
				'app-editor-container',
				'app-data-picker-view',
				`app-data-picker-view-${name}`,
			]"
			showSearch
			v-model:value="value"
			:disabled="disabled"
			:filterOption="false"
			dropdownClassName="dropdown__embed-view"
			:placeholder="
				placeholder ? placeholder : $t('common.datapickerview.placeholder')
			"
			:open="open"
			@change="onChange"
			@focus="onFocus"
			@blur="onBlur"
		>
			<template #suffixIcon>
				<span class="app-data-picker-dropdown-select-icon">
					<CloseCircleOutlined
						v-show="value"
						class="close-icon suffix-icon"
						@click="clear"
					/>
					<DownOutlined
						v-show="!open"
						@click="switchAppAc"
						class="down-icon suffix-icon"
					/>
					<UpOutlined
						v-show="open"
						@click="switchAppAc"
						class="up-icon suffix-icon"
					/>
					<SearchOutlined v-if="pickUpView" class="" @click="openView" />
					<LinkOutlined v-if="linkView" @click="openLinkView" />
				</span>
			</template>
			<template #dropdownRender>
				<component
					:is="pickUpView"
					:context="context"
					:viewParams="props.viewParams"
					:name="pickUpView"
					@mousedown="(e: Event) => e.preventDefault()"
					@view-action="handleViewAction"
				/>
			</template>
		</a-select>
		<div v-else class="data-picker-view__embed-view">
			<component
				:is="pickUpView"
				:context="context"
				:viewParams="props.viewParams"
				:name="pickUpView"
				@view-action="handleViewAction"
			/>
		</div>
	</a-form-item-rest>
</template>

<script setup lang="ts">
import { Ref, ref } from 'vue';
import { FormItemRest } from 'ant-design-vue';
import {
	DownOutlined,
	UpOutlined,
	CloseCircleOutlined,
	SearchOutlined,
	LinkOutlined,
} from '@ant-design/icons-vue';
import {
	deepCopy,
	IParam,
	IEvent,
	IContext,
	isExistAndNotEmpty,
	IViewDetail,
} from '@/core';
import { dataPickerViewProps } from './data-picker-view';
import { handleEditorNavParams } from '@/hooks/use-editor';
interface EditorEmit {
	(name: 'component-action', value: IEvent<string>): void;
}
const props = defineProps(dataPickerViewProps);
const emit = defineEmits<EditorEmit>();

const { navContext, navViewParam } = handleEditorNavParams(props);
let items: Ref<any[]> = ref([]);
const open = ref(false);
//管理菜单开关状态
const switchAppAc = () => {
	open.value = !open.value;
};

//聚焦状态
const onFocus = () => {
	open.value = true;
};

const onBlur = () => {
	open.value = false;
};
/**
 * @description 填充外键值附加数据
 * @param item 选中数据
 */
const fillPickUpData = (item: IParam) => {
	if (props.pickUpData) {
		let pickUpDataArray: string[] = props.pickUpData.split(';');
		if (pickUpDataArray && pickUpDataArray.length > 0) {
			for (let i = 0; i < pickUpDataArray.length; i++) {
				if (item) {
					emit('component-action', {
						name: pickUpDataArray[i],
						action: 'valueChange',
						data: item[pickUpDataArray[i]],
					});
				} else {
					emit('component-action', {
						name: pickUpDataArray[i],
						action: 'valueChange',
						data: null,
					});
				}
			}
		}
	}
};

//打开链接视图
const openLinkView = (event: any): void => {
	event.preventDefault();
	event.stopPropagation();
	if (
		!props.data ||
		!props.valueItem ||
		!props.data.hasOwnProperty(props.valueItem)
	) {
		const error = App.ts('common.generic.error', '错误');
		const formdataexception = App.ts(
			'common.datapicker.formdataexception',
			'表单数据异常！'
		);
		const valueitemexception = App.ts(
			'common.datapicker.valueitemexception',
			'值项异常'
		);
		if (!props.data) {
			console.error(error, formdataexception);
		} else {
			console.error(error, valueitemexception);
		}
		return;
	}
	if (!props.linkView) {
		return;
	}
	// 公共参数处理
	let data: any = {
		param: {},
		context: {},
	};
	Object.assign(data.param, navViewParam);
	Object.assign(data.context, navContext);

	// 参数处理
	let _context = data.context;
	let _param = data.param;
	Object.assign(_context, { [props.deKeyField]: props.data[props.valueItem] });

	const view = App.getAppViewConfig()?.[props.linkView];
	App.getOpenViewHelper().openPage(view, _context, _param);
};

// 打开一般视图
const openView = (event: any) => {
	event.preventDefault();
	event.stopPropagation();
	if (props.disabled) {
		return;
	}
	if (!props.pickUpView) {
		return;
	}
	const view = App.getAppViewConfig()?.[props.pickUpView];
	if (!view) {
		return;
	}
	const params: IParam = {};
	const tempViewParams = deepCopy(navViewParam);
	//多选
	if (props.multiple) {
		let selectedData: IParam[] = [];
		try {
			selectedData = props.value ? JSON.parse(props.value) : [];
		} catch (error) {
			selectedData = [];
		}
		Object.assign(tempViewParams, { selectedData: selectedData });
	} else {
		const selectedData: IParam = {};
		if (
			props.data &&
			props.valueItem &&
			isExistAndNotEmpty(props.data[props.valueItem])
		) {
			Object.assign(selectedData, { srfkey: props.data[props.valueItem] });
		}
		if (isExistAndNotEmpty(`${props.value}`)) {
			Object.assign(selectedData, { srfmajortext: props.value });
		}
		Object.assign(tempViewParams, { selectedData: [selectedData] });
	}
	//打开视图
	if (
		!Object.is(view.openMode, 'POPOVER') &&
		!Object.is(view.openMode, 'DRAWER')
	) {
		Object.assign(params, { openMode: 'POPUPMODAL' });
	}
	if (Object.is(params.openMode, 'POPUPMODAL')) {
		openPopupModal(view, deepCopy(navContext), tempViewParams);
	} else if (Object.is(view.openMode, 'POPOVER')) {
		openPopOver(view, deepCopy(navContext), tempViewParams);
	} else if (Object.is(view.openMode, 'DRAWER')) {
		openDrawer(view, deepCopy(navContext), tempViewParams);
	}
};

//气泡卡片模式打开视图
const openPopOver = (view: IViewDetail, context: IContext, params: IParam) => {
	App.getOpenViewHelper()
		.openPopover(view, context, params)
		.then((response: any) => {
			if (response.ok) {
				doEditorEmit(response.data);
			}
		});
};
//抽屉模式打开视图
const openDrawer = (view: IViewDetail, context: IContext, params: IParam) => {
	App.getOpenViewHelper()
		.openRightDrawer(view, context, params)
		.then((response: any) => {
			if (response.ok) {
				doEditorEmit(response.data);
			}
		});
};
//模态模式打开视图
const openPopupModal = (
	view: IViewDetail,
	context: IContext,
	params: IParam
) => {
	App.getOpenViewHelper()
		.openModal(view, props.context, params)
		.then((response: any) => {
			if (response.ok) {
				doEditorEmit(response.data);
			}
		});
};

// 编辑器抛值
const doEditorEmit = (data: any[]): any => {
	let selects: Array<any> = [];
	data.forEach((select: any) => {
		selects.push({
			[props.deKeyField]: select[props.deKeyField],
			[props.deMajorField]: select[props.deMajorField],
		});
		let index = items.value.findIndex((item) =>
			Object.is(item[props.deKeyField], select[props.deKeyField])
		);
		if (index < 0) {
			items.value.push({
				[props.deMajorField]: select[props.deMajorField],
				[props.deKeyField]: select[props.deKeyField],
			});
		}
	});
	let value = selects.length > 0 ? JSON.stringify(formatValue(selects)) : '';
	emit('component-action', {
		name: `${props.name}`,
		action: 'valueChange',
		data: value,
	});
	return;
};

//格式化
const formatValue = (value: any[]) => {
	let result = [];
	if (props.deKeyField !== 'srfkey' || props.deMajorField !== 'srfmajortext') {
		value.forEach((item: any) => {
			result.push({
				srfmajortext: item[props.deMajorField],
				srfkey: item[props.deKeyField],
			});
		});
	} else {
		result = value;
	}
	return result;
};

//过滤数据
const filterOption = (inputValue: string, option: IParam) => {
	return (
		option[props.deMajorField]
			.toUpperCase()
			.indexOf(inputValue.toUpperCase()) >= 0
	);
};

//选中数据
const onSelect = (value: any) => {
	const selectItem = items.value.find((item: IParam) =>
		Object.is(item[props.deKeyField!], value)
	);
	emit('component-action', {
		name: `${props.name}`,
		action: 'valueChange',
		data: selectItem[props.deMajorField!],
	});
	emit('component-action', {
		name: `${props.valueItem}`,
		action: 'valueChange',
		data: selectItem[props.deKeyField!],
	});
	fillPickUpData(selectItem);
};

//值变化
const onChange = (select: any, dateString: any) => {
	emit('component-action', {
		name: props.name as string,
		action: 'valueChange',
		data: select,
	});
};

//清空数据
const clear = () => {
	emit('component-action', {
		name: `${props.name}`,
		action: 'valueChange',
		data: '',
	});
	if (props.valueItem) {
		emit('component-action', {
			name: `${props.valueItem}`,
			action: 'valueChange',
			data: '',
		});
	}
};

const handleViewAction = (name: string, action: any, data: IParam[]) => {
	if (action == 'viewDataChange') {
		open.value = false;
		let value_temp: string[] = [];
		let majorValue: string[] = [];
		data.forEach((item: any) => {
			value_temp.push(item[props.deKeyField]);
			majorValue.push(item[props.deMajorField]);
		});
		emit('component-action', {
			name: `${props.name}`,
			action: 'valueChange',
			data: majorValue.join(','),
		});
		emit('component-action', {
			name: `${props.valueItem}`,
			action: 'valueChange',
			data: value_temp.join(','),
		});
	} else if (action == 'viewClose') {
		open.value = false;
	}
};
</script>
